package i.i.myapplication.controller;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import i.i.myapplication.R;

import i.i.myapplication.model.Music;

public class MusicAdapter extends BaseAdapter {

    private List<Music> musicList;
    private LayoutInflater inflater;
    private OnPlayClickListener playClickListener;

    public interface OnPlayClickListener {
        void onPlayClick(int position);
    }

    public MusicAdapter(Context context, List<Music> musicList, OnPlayClickListener listener) {
        this.musicList = musicList;
        this.inflater = LayoutInflater.from(context);
        this.playClickListener = listener;
    }

    @Override
    public int getCount() {
        return musicList.size();
    }

    @Override
    public Object getItem(int position) {
        return musicList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    static class ViewHolder {
        ImageView songPic;
        TextView songName;
        TextView singerName;
        ImageView songEnter;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.music_item_layout, parent, false);
            holder = new ViewHolder();
            holder.songPic = convertView.findViewById(R.id.song_pic);
            holder.songName = convertView.findViewById(R.id.song_name);
            holder.singerName = convertView.findViewById(R.id.name);
            holder.songEnter = convertView.findViewById(R.id.song_enter);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Music music = musicList.get(position);
        holder.songPic.setImageResource(music.songPicResId);
        holder.songName.setText(music.songName);
        holder.singerName.setText(music.singerName);

        holder.songEnter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (playClickListener != null) {
                    playClickListener.onPlayClick(position);
                }
            }
        });

        return convertView;
    }
}

